package top.xia17.plugins.fast.common.crypto.asymmetric;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import top.xia17.plugins.fast.common.exceptions.BadRequestException;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

/**
 * rsa加密
 * @author xia17
 * @date 2020/7/17 11:30
 */
@Component
@RequiredArgsConstructor
public class RsaUtil implements InitializingBean {

    private final RsaProperties rsaProperties;
    private RSA rsa;

    @Override
    public void afterPropertiesSet(){
        if (StrUtil.isBlank(rsaProperties.getPrivateKey()) || StrUtil.isBlank(rsaProperties.getPublicKey())){
            rsa = null;
        }else {
            rsa = new RSA(rsaProperties.getPrivateKey(),rsaProperties.getPublicKey());
        }
    }

    /**
     * 私钥 解密
     *
     * @param data 待解密的字符串
     * @return 解密后的字符串
     */
    public String decryptStr(String data){
        if (rsa == null){
            throw new BadRequestException("未在配置文件中声明rsa的私钥或者公钥");
        }
        return rsa.decryptStr(data, KeyType.PrivateKey);
    }

    /**
     * 公钥 加密
     * @param data 待加密的字符串
     * @return 加密后的字符串
     */
    public String encryptStr(String data){
        if (rsa == null){
            throw new BadRequestException("未在配置文件中声明rsa的私钥或者公钥");
        }
        return rsa.encryptBase64(data, KeyType.PublicKey);
    }



}
